//
//  XYUserHelper.m
//  PeiJue
//
//  Created by lxy on 2017/12/6.
//  Copyright © 2017年 lixiya. All rights reserved.
//

#import "XYUserHelper.h"
#import <MKEnvObserver/MKEnvObserver.h>

static NSString *kAuthorizationHeaderField = @"Authorization";
static NSString *kCacheDefaultToken = @"defaultToken";

@interface XYUserHelper()
@property (nonatomic, strong, readwrite) NSString *token;
@property (nonatomic, strong) MKEnvObserverCenter *observerCenter;
@end

@implementation XYUserHelper

+ (instancetype)shareInstance {
    static XYUserHelper *userHelper = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        userHelper = [[XYUserHelper alloc] init];
    });
    return userHelper;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _observerCenter = [[MKEnvObserverCenter alloc] init];
        if (self.token) {
            NSString *token = [[XYCacheHelper shareInstance] getObjectFromDocumentDirForKey:kCacheDefaultToken];
            NSString *bearerToken = [NSString stringWithFormat:@"Bearer %@",token];
            //设置Authorization请求头
            [self setHeaderFieldValue:bearerToken forKey:kAuthorizationHeaderField];
        }
    }
    return self;
}

- (void)addObserver:(id<XYUserHelperDelegete>)observer {
    [_observerCenter addEnvObserver:observer];
}

- (void)removeObserver:(id<XYUserHelperDelegete>)observer {
    [_observerCenter removeEnvObserver:observer];
}

#pragma mark - Privates
- (void)cacheUserToken:(NSString *)token {
    _token = token;
    [[XYCacheHelper shareInstance] cacheToDocumentDirWithObject:token forKey:kCacheDefaultToken];
    NSString *bearerToken = nil;
    if (token) {
        bearerToken = [NSString stringWithFormat:@"Bearer %@",token];
    }
    //设置Authorization请求头
    [self setHeaderFieldValue:bearerToken forKey:kAuthorizationHeaderField];
}

#pragma mark - Publics
- (void)noticeNeedAuthByRequestTokenInvalid {
    //..token过期退出的操作
    [_observerCenter noticeObervers:@selector(needAuthByRequestTokenInvalid)];
    
}


#pragma mark - Request



#pragma mark - Getters
- (BOOL)isLogin {
    return self.token ? YES : NO;
}

- (NSString *)token {
    NSString *token = [[XYCacheHelper shareInstance] getObjectFromDocumentDirForKey:kCacheDefaultToken];
    if (token) {
        _token = token;
    }
    return _token;
}

@end
